package com.huawei.cloud.phone.management.common.security;

import com.huawei.cloud.phone.management.common.utils.RandomStringUtils;
import com.huawei.cloud.phone.management.common.exception.SystemInnerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class Md5EncryptionServiceImpl implements EncryptionService {
    private static final String SALT = "1@!";

    @Override
    public String encrypt(@NonNull String plainText) {
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            log.error("get md5 digest failed", e);
            throw new SystemInnerException();
        }

        byte[] digestData = messageDigest.digest((plainText + SALT).getBytes(StandardCharsets.UTF_8));
        return RandomStringUtils.bytesToHex(digestData);
    }

    @Override
    public String decrypt(@NonNull String cipherText) {
        log.error("MD5 does not support decryption.");
        throw new SystemInnerException();
    }
}
